/**
 * Created by mooshroom on 2018/1/11.
 */
const http=require("http");
const exec=require('child_process').exec
var server=new http.Server();
var fs=require('fs')

server.on("request",function(req,res){


    //获取清请求数据
    var data=''
    req.on('data',function (chunk) {
        data+=chunk
    })
    req.on('end',function () {
        data=JSON.parse(data)

        // console.log(data.password)

        //安全防护
        if(data.password!=='chjsyjs'){
            res.end()
            return console.log('接收到错误密码的push更新请求')
        }

        //返回请求
        res.writeHead(200,{
            "content-type":"text/plain"
        });

        //执行shell脚本更新项目
        var projectName=data.project.name

        console.log('开始更新项目：'+projectName)

        //处理榨汁机项目的非正规命名
        if(projectName==='JuicerManager_web'){
            projectName='juicermanager_web'
        }

        fs.exists('/server/source/'+projectName,function(exists){
            if(exists){
                //执行命令
                //多行命令必须一口气说完，用分号隔开，否则下面一句话接不上上面一句话
                exec('export PATH=/usr/libexec/git-core/:$PATH; cd /server/source/'+projectName+'; git pull origin master',function (error,stdout) {
                    if(error!==null){
                        //有失败的情况
                        res.write("更新失败！");
                        res.end();
                        return console.log("exec error： " + error)
                    }

                    console.log(stdout)
                    console.log(projectName+'更新成功！')


                    res.write('版本：'+data.after+"  于"+new Date()+"更新成功！");
                    res.end();
                })
            }else{
                // console.log(data.project)
                var cloneURL=data.project.url.replace('https://','https://mooshroom:zw2580\!\!@')

                exec('export PATH=/usr/libexec/git-core/:$PATH; cd /server/source/; git clone '+cloneURL,function (error,stdout) {
                    if(error!==null){
                        //有失败的情况
                        res.write("克隆失败！");
                        res.end();
                        return console.log("exec error： " + error)
                    }

                    console.log(stdout)
                    console.log(projectName+'克隆成功！')


                    res.write('版本：'+data.after+"  于"+new Date()+"克隆成功！");
                    res.end();
                })
            }
        })

    })


});
server.listen(3000);

console.log('Server running at http://127.0.0.1:3000/')